package com.qf.thread.then;

import java.util.concurrent.*;

public class RunAfterBothDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                5,
                20,
                2000,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(10000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );

        // 1.准备任务1
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务1开始执行");
            return "任务1";
        }, executor);

        // 2.准备任务2
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务2开始执行");
            return "任务2";
        }, executor);

//        // 3.等任务1和任务2执行完后调用任务3，任务3不需要前两个任务的返回结果，任务3没有返回值
//        future2.runAfterBothAsync(future1, () -> {
//            System.out.println("任务3开始执行");
//        }, executor);

//        // 3.等任务1和任务2执行完后调用任务3，任务3需要前两个任务的返回结果，任务3没有返回值
//        future2.thenAcceptBothAsync(future1, (resp1, resp2) -> {
//            System.out.println("任务3开始执行,resp1:" + resp1 + ",resp2:" + resp2);
//        }, executor);

//         3.等任务1和任务2执行完后调用任务3，任务3需要前两个任务的返回结果，任务3有返回值
        CompletableFuture<String> future3 = future2.thenCombineAsync(future1, (resp1, resp2) -> {
            System.out.println("任务3开始执行,resp1:" + resp1 + ",resp2:" + resp2);
            return "任务3";
        }, executor);

        System.out.println(future3.get());

    }
}
